package com.xebest.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.WeChatSupplierCentorDto;
import com.xebest.api.dto.WeChatSupplierOrderLogisticsDTO;
import com.xebest.api.dto.WeChatSupplierOrderLogisticsDetailDTO;
import com.xebest.api.dto.WeChatSupplierQueryDTO;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.constant.XeConstans;
import com.xebest.web.form.XeVenOrderLogisticsForm;
import com.xebest.web.mapper.read.WeChatSupplierReadMapper;
import com.xebest.web.mapper.read.XeVenOrderLogisticsReadMapper;
import com.xebest.web.mapper.read.XeVenOrderReadMapper;
import com.xebest.web.model.*;
import com.xebest.web.service.WeChatSupplierService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xebest on 2017/11/2.
 */
@Service
public class WeChatSupplierServiceImpl implements WeChatSupplierService{

    @Autowired
    private WeChatSupplierReadMapper weChatSupplierReadMapper;
    @Autowired
    private XeVenOrderReadMapper xeVenOrderReadMapper;
    @Autowired
    private XeVenOrderLogisticsReadMapper xeVenOrderLogisticsReadMapper;
    @Autowired
    private XeBaseUtil xeBaseUtil;

    @Override
    public List<WeChatSupplierOrdersEntity> queryOrderList(WeChatSupplierQueryDTO form) {
    	Integer orderStatus = form.getOrderStatus();
    	if (null != orderStatus) {
    		if (form.getOrderStatus().equals(XeConstans._XE_SEVEN)) {
				form.setOrderStatus(null);
				form.setPayStatus(2);
			}
			//v3.1.5 微信生意管家修改 查询代发货时只查询代发货的数据不再查询待分配（5）和待审核(6)的数据
//			if (orderStatus.equals(XeConstans._XE_THREE)) {
//                form.setOrderStatus(null);
//                form.setOrderStatu(new String[]{"3","5","6"});
//            }
            if (orderStatus.equals(XeConstans._XE_EIGHT)) {
                form.setOrderStatus(null);
                form.setPromotOrderType(4);
            }
    	}
        Map<String,Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orderForm",form);
        if (XeConstans._XE_TWO == form.getAdminFlag()) {
            if (StringUtils.isNotBlank(form.getRoleIds())) {
                paramMap.put("roleId",form.getRoleIds().split(","));
            } else {
                paramMap.put("roleId",null);
            }
        }
        List<WeChatSupplierOrdersEntity> actionList = weChatSupplierReadMapper.queryOrderList(paramMap);
        if (null != actionList && actionList.size() > XeConstans._XE_ZERO) {
            for (int i = 0; i < actionList.size(); i++) {
                WeChatSupplierOrdersEntity orderEntity = actionList.get(i);
              /*  if (null != orderStatus && orderStatus.equals(XeConstans._XE_SEVEN)) {
                	if (orderEntity.getOrderStatus().equals(XeConstans._XE_FIVE)) {
                		orderEntity.setOrderStatus(7);
                	}
                }*/
                BigDecimal epayReceAmt = orderEntity.getEpayReceAmt();
                if (orderEntity.getPayType().equals(XeConstans._XE_ONE) && orderEntity.getConfirmSendNum().equals(XeConstans._XE_TWO)) {
                    orderEntity.setPayAmount(epayReceAmt);
                }
                if (orderEntity.getPayType().equals(XeConstans._XE_FOUR) && orderEntity.getPayStatus().equals(XeConstans._XE_TWO) && !(orderEntity.getOrderStatus().equals(XeConstans._XE_FOUR))) {
                	orderEntity.setOrderStatus(7);
                }
                //v3.1.5 微信生意管家修改 待分配（5）和待审核(6) 显示其真实的订单状态
//                if (orderEntity.getOrderStatus().equals(XeConstans._XE_FIVE) || orderEntity.getOrderStatus().equals(XeConstans._XE_SIX)) {
//            		orderEntity.setOrderStatus(3);
//            	}
                paramMap.put("orderId",orderEntity.getOrderId());
                List<WeChatSupplierOrderDetailEntity> list = weChatSupplierReadMapper.queryOrderDetailByOrderId(paramMap);
                orderEntity.setOrderDetailList(list);
                /*if (orderEntity.getConfirmSendNum().equals(XeConstans._XE_TWO)) {
                    orderEntity.setPayAmount(orderEntity.getEpayReceAmt());
                }*/
            }
        }
        return actionList;
    }

    @Override
    public WeChatSupplierOrderEntity queryOrderDetail(WeChatSupplierQueryDTO form) {
        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("orderId",form.getOrderId());
        resultMap.put("userCode",form.getUserCode());
        WeChatSupplierOrderEntity orderEntity = weChatSupplierReadMapper.queryOrderDetail(resultMap);
        if (null == orderEntity) {
        	return orderEntity;
        }
        BigDecimal epayReceAmt = orderEntity.getEpayReceAmt();
        orderEntity.setEpayReceAmt(orderEntity.getPayAmount());
        if (orderEntity.getPayType().equals(XeConstans._XE_ONE) && orderEntity.getConfirmSendNum().equals(XeConstans._XE_TWO)) {
            orderEntity.setEpayReceAmt(epayReceAmt);
        }
        if (orderEntity.getPayType().equals(XeConstans._XE_FOUR) && orderEntity.getPayStatus().equals(XeConstans._XE_TWO) && !(orderEntity.getOrderStatus().equals(XeConstans._XE_FOUR))) {
        	orderEntity.setOrderStatus(7);
		}
		//待审核和待分配的订单显示其真实的订单状态
//        if (orderEntity.getOrderStatus().equals(XeConstans._XE_FIVE) || orderEntity.getOrderStatus().equals(XeConstans._XE_SIX)) {
//            orderEntity.setOrderStatus(3);
//        }
        String caCityName = xeBaseUtil.getAreaName(Integer.parseInt(orderEntity.getCaCityId().trim()));
        String caProvinceName = xeBaseUtil.getAreaName(Integer.parseInt(orderEntity.getCaProvinceId().trim()));
        String caAreaName = "";
        if (StringUtils.isNotBlank(orderEntity.getCaAreaId())) {
            caAreaName = xeBaseUtil.getAreaName(Integer.parseInt(orderEntity.getCaAreaId().trim()));
        }
        orderEntity.setCaArea(caProvinceName+caCityName+caAreaName+orderEntity.getCaStreet());
        orderEntity.setCaPhone("***********");
        orderEntity.setCaConsignee(orderEntity.getCaConsignee().substring(0,1)+"**");
        return orderEntity;
    }

    @Override
    public WeChatSupplierOrderLogisticsDTO queryOrderlogistics(WeChatSupplierQueryDTO form) {
        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userCode",form.getUserCode());
        resultMap.put("orderId",form.getOrderId());
        WeChatSupplierOrderLogisticsDTO orderLogistics = null;
        XeVenOrderLogisticsForm logisticsForm = new XeVenOrderLogisticsForm();
        logisticsForm.setOrderId(form.getOrderId());
        logisticsForm.setUserCode(form.getUserCode());
        List<XeVenOrderLogistics> logisticsList = xeVenOrderLogisticsReadMapper.selectLogisticsList(logisticsForm);
        if(logisticsList != null && logisticsList.size() > 0){
            orderLogistics = JSONObject.parseObject(JSONObject.toJSONString(logisticsList.get(0)), WeChatSupplierOrderLogisticsDTO.class);

            Map<String,Object> map = weChatSupplierReadMapper.queryOrderAddress(resultMap);
            orderLogistics.setCaConsignee(map.get("caConsignee").toString().substring(0,1)+"**");
            orderLogistics.setCaPhone("***********");
            String caCityName = xeBaseUtil.getAreaName(Integer.parseInt(map.get("caCityId").toString().trim()));
            String caProvinceName = xeBaseUtil.getAreaName(Integer.parseInt(map.get("caProvinceId").toString().trim()));
            String caAreaName = "";
            if (map.containsKey("caCityId")) {
                caAreaName = xeBaseUtil.getAreaName(Integer.parseInt(map.get("caAreaId").toString().trim()));
            }
            orderLogistics.setCaArea(caProvinceName+caCityName+caAreaName+map.get("caStreet").toString());
            if(orderLogistics != null){
                List<XeVenOrderLogisticsDetail> orderLogisticsDetailList = xeVenOrderLogisticsReadMapper.listLogisticsDetail(form.getOrderId(), "2");
                if(orderLogisticsDetailList != null && orderLogisticsDetailList.size() > 0){
                    orderLogistics.setOrderLogisticsDetailList(JSONObject.parseArray(JSONObject.toJSONString(orderLogisticsDetailList), WeChatSupplierOrderLogisticsDetailDTO.class));
                }
            }
        }
        return orderLogistics;
    }

    @Override
    public WeChatSupplierCentorDto queryPersonalCenter(WeChatSupplierQueryDTO form) {
        WeChatSupplierCentorDto dto = new WeChatSupplierCentorDto();
        Map<String,Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode",form.getUserCode());
        Map<String,Object> map = xeVenOrderReadMapper.queryCountPringByDay(paramMap);
        BigDecimal monthTotalAmount = xeVenOrderReadMapper.queryMonthTotalAmount(paramMap);
        BigDecimal monthTradeUserNum = xeVenOrderReadMapper.queryMonthTradeUserNum(paramMap);
        //v3.1.5 add 微信生意管家查询 待发货时只查询最近三个月的订单
        paramMap.put("startTime",LocalDate.now().plusMonths(-3));
        BigDecimal waitDelivery = xeVenOrderReadMapper.queryWaitSendOrderNumForWeChat(paramMap);
        dto.setSumDayAmount(map.containsKey("sumAmount") ? new BigDecimal(map.get("sumAmount").toString()) : new BigDecimal("0"));
        dto.setSumMonthAmount(monthTotalAmount);
        dto.setCountDayOrder(map.containsKey("countOrder") ? Integer.parseInt(map.get("countOrder").toString()) : 0);
        dto.setCountMonthTranOrder(monthTradeUserNum.intValue());
        dto.setWaitSendOrderNum(waitDelivery);
        return dto;
    }

    @Override
    public WeChatSupplierCentorDto queryWaitDelivery(WeChatSupplierQueryDTO form) {
        WeChatSupplierCentorDto dto = new WeChatSupplierCentorDto();
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("userCode",form.getUserCode());
        Integer waitDelivery = weChatSupplierReadMapper.queryWaitDelivery(params);
        dto.setWaitSendOrderNum(new BigDecimal(waitDelivery));
        return dto;
    }
    public static void main(String[] args){
      System.out.println(LocalDate.now());
      System.out.println(LocalDate.now().plusMonths(-3));
    }
}
